package com.xpmusic.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
public class DBUtil {
    private static SqlSession sqlSession = null;
    private static InputStream inputStream = null;
    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * 读取配置文件，通过SqlSessionFactory创建SqlSession
     * @return sqlSession
     */
    public static SqlSession openSessionConnection(){
        String resource = "config/SqlMapConfig.xml";
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }

    /**
     * 关闭资源
     */
    public static void close(){
        try {
            sqlSession.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
